package api;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.config.SocketConfig;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;

import java.io.IOException;

/**
 * 小象代理短效代理IP示例 - JAVA，类库 httpclient
 *
 * @author xxdl
 */
public class HttpClient45Demo {

    // 应用账号（请替换为真实账号）
    private static String appKey = "appKey";
    // 应用密码（请替换为真实密码）
    private static String appSecret = "appSecret";

    private static String api = "http://api.xiaoxiangdaili.com/ip/get?appKey=%s&appSecret=%s&cnt=1&wt=text";
    private static int timeout = 10000;

    private static HttpClientBuilder clientBuilder = null;

    static {
        // JDK 8u111版本后，目标页面为HTTPS协议，启用proxy用户密码鉴权
        System.setProperty("jdk.http.auth.tunneling.disabledSchemes", "");

        SocketConfig socketConfig = SocketConfig.custom().setSoTimeout(timeout).build();

        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(appKey, appSecret));

        clientBuilder = HttpClients.custom()
                .disableAutomaticRetries()
                .setDefaultSocketConfig(socketConfig)
                .setDefaultCredentialsProvider(credsProvider);
    }

    private static HttpHost getProxy() throws IOException {
        //构造响应对象
        CloseableHttpResponse httpResp = null;
        try {
            RequestConfig requestConfig = RequestConfig.custom()
                    .setConnectionRequestTimeout(timeout)
                    .setConnectTimeout(timeout)
                    .setSocketTimeout(timeout)
                    .setExpectContinueEnabled(false)
                    .setProxy(null)
                    .build();

            HttpClientContext localContext = HttpClientContext.create();
            //构造请求对象
            HttpGet httpReq = new HttpGet(String.format(api, appKey, appSecret));
            httpResp = clientBuilder
                    .setDefaultRequestConfig(requestConfig)
                    .build().execute(httpReq, localContext);

            if (httpResp.getStatusLine().getStatusCode() == 200) {
                //获取响应实体
                String content = IOUtils.toString(httpResp.getEntity().getContent(), "UTF-8");
                System.out.println("API response: " + content);
                if (!StringUtils.isEmpty(content)) {
                    String[] splits = content.split(":");
                    if (splits.length == 2) {
                        return new HttpHost(splits[0], Integer.parseInt(splits[1]));
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            httpResp.close();
        }
        return null;
    }

    public static void getUrlContent(String url) throws IOException {
        //构造响应对象
        CloseableHttpResponse httpResp = null;
        try {
            HttpHost proxy = getProxy();
            RequestConfig requestConfig = RequestConfig.custom()
                    .setConnectionRequestTimeout(timeout)
                    .setConnectTimeout(timeout)
                    .setSocketTimeout(timeout)
                    .setExpectContinueEnabled(false)
                    .setProxy(proxy)
                    .build();

            HttpClientContext localContext = HttpClientContext.create();
            httpResp = clientBuilder
                    .setDefaultRequestConfig(requestConfig)
                    .build().execute(new HttpGet(url), localContext);
            //获取响应实体
            String content = IOUtils.toString(httpResp.getEntity().getContent(), "UTF-8");
            System.out.println("Target response：" + content);

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            httpResp.close();
        }

    }

    public static void main(String[] args) throws Exception {
        // 要访问的目标页面
        String targetUrl = "http://httpbin.org/ip";
        for (int i = 0; i < 3; i++) {
            getUrlContent(targetUrl);
            Thread.sleep(10000);
        }
    }
}
